import { global } from '@awey/maxios'
import { showLoadingToast, allowMultipleToast } from '@/common/toast'
allowMultipleToast()

const initGlobalAjax = (): void => {
  let toastCount = 0
  let toast: any = null
  global({
    axiosConfig: {
      baseURL: '/api',
      headers: {
        global: '123'
      }
    },
    // 统一处理loading
    loading(status) {
      if (status) {
        if (toast === null) {
          toast = showLoadingToast({
            duration: 0,
            forbidClick: true,
            loadingType: 'spinner'
          })
        }
        toastCount++
      } else {
        toastCount--
        if (toast !== null && toastCount === 0) {
          toast.close()
          toast = null
        }
      }
    },
    // 业务返回 返回true success 被执行，否则 bizError 被执行
    indicator(response) {
      return response.data.code !== 1
    },
    // 向应拦截器
    extractor(response) {
      return response.data.data
    },
    // 业务错误处理 indicator => false
    bizError(data) {
      console.log(data, '---biz error from global')
    },
    // 接口错误处理
    error(err) {
      console.log('err', err)
    },
    // 成功
    success() {
      console.log('success from global')
    },
    // 最终都要执行
    anyway() {
      console.log('anyway from global')
    }
  })
}
export default initGlobalAjax
